package com.kgc.dubbo.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.dubbo.entity.QgOrder;
import com.kgc.dubbo.entity.QgUser;
import com.kgc.dubbo.exception.OrderException;
import com.kgc.dubbo.service.LocalOrderService;
import com.kgc.dubbo.service.QgOrderService;
import com.kgc.dubbo.utils.Constants;
import com.kgc.dubbo.utils.compoent.RedisTools;
import com.kgc.dubbo.vo.QgGoodsVO;
import com.kgc.dubbo.vo.QgOrderPayVO;
import com.kgc.dubbo.vo.QgOrderVO;
import com.kgc.dubbo.vo.RespResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LocalOrderServiceImpl implements LocalOrderService {
    @Reference
    private QgOrderService qgOrderService;
    @Autowired
    private RedisTools redisTools;
    @Override
    public RespResult orderListByUser(String id, String token) throws Exception {
        //1.获取用户信息
        QgUser qgUser = redisTools.getObject(token,QgUser.class);
        //2.去redis中查询商品信息
        QgGoodsVO goodsVO = redisTools.getObject(Constants.GOODS_PREFIX + id, QgGoodsVO.class);
        List<QgOrderVO> orderVOList = new ArrayList<>();
        Map<String,Object> params = new HashMap<>();
        params.put("goodsId",id);
        params.put("userId",qgUser.getId());
        List<QgOrder> qgOrderList = qgOrderService.getQgOrderListByMap(params);
        for (QgOrder qgOrder:qgOrderList){
            QgOrderVO orderVO = new QgOrderVO();
            BeanUtils.copyProperties(qgOrder,orderVO);
            //设置图片地址
            orderVO.setGoodsImg(goodsVO.getGoodsImg());
            orderVOList.add(orderVO);
        }
        return RespResult.ok(orderVOList);
    }

    @Override
    public RespResult getOrderById(String orderId) throws Exception {
        QgOrder qgOrder = qgOrderService.getQgOrderById(orderId);
        QgOrderPayVO orderPayVO = new QgOrderPayVO();
        BeanUtils.copyProperties(qgOrder,orderPayVO);
        orderPayVO.setPayAmount(qgOrder.getAmount());
        return RespResult.ok(orderPayVO);
    }

    @Override
    public RespResult getOrderByOrderNo(String orderNo) throws Exception {
        Map<String,Object> params = new HashMap<>();
        params.put("orderNo",orderNo);
        List<QgOrder> qgOrderList = qgOrderService.getQgOrderListByMap(params);
        if (qgOrderList!=null && qgOrderList.size()==1){
            return RespResult.ok(qgOrderList.get(0));
        }
        return RespResult.build(OrderException.ORDER_NOT_FOUND.getCode(),
                OrderException.ORDER_NOT_FOUND.getMessage());
    }
}
